import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Pagination, message, Tag } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import {
  searchUser,
  getAdminListLength, returnListData, getBanList, banUser, hotUser, deleteUser
} from '@/api/userInfo/index';
import { tracking } from '@/core/utils/operation'



const UserList = () => {
  const [adminAccount, setAdminAccount] = useState('');
  const [tableData, setTableData] = useState([]);
  const [adminTotal, setAdminTotal] = useState(0);
  const [paginationData, setPaginationData] = useState({
    pageCount: 1,
    currentPage: 1,
  });

  const name = JSON.parse(localStorage.getItem('userInfo')).name




  const fetchUserList = async (page = 1) => {
    const res = await returnListData(page, '用户');
    setTableData(res);
  };

  const fetchAdminListLength = async () => {
    const res = await getAdminListLength('用户');
    setAdminTotal(res.length);
    setPaginationData((prev) => ({
      ...prev,
      pageCount: Math.ceil(res.length / 10),
    }));
  };

  const searchUserByAccount = async () => {
    try {
      if (!adminAccount) {
        const data = await returnListData(paginationData.currentPage, '用户');
        setTableData(data);
      } else {
        const data = await searchUser(adminAccount, '用户');
        setTableData(data);
      }
      setPaginationData(prev => ({
        ...prev,
        pageCount: 1,
      }));
    } catch (error) {
      console.error('Error searching admin:', error);
    }
  };


  const banUserList = async () => {
    const res = await getBanList();
    setTableData(res);
  };

  const banUserById = async (id) => {
    const res = await banUser(id);
    if (res.status === 0) {
      message.success('冻结用户成功');
      fetchAdminListLength();
      fetchUserList(paginationData.currentPage);
    } else {
      message.error('冻结用户失败');
    }
  };

  const hotUserById = async (id) => {
    const res = await hotUser(id);
    if (res.status === 0) {
      message.success('解冻用户成功');
      fetchAdminListLength();
      fetchUserList(paginationData.currentPage);
    } else {
      message.error('解冻用户失败');
    }
  };

  const handleDeleteUser = async (record) => {
    const res = await deleteUser(record.id, record.account);
    if (res.status === 0) {
      message.success('删除用户成功');
      await tracking('管理员', name, record.name, '高级')
      fetchAdminListLength();
      fetchUserList(paginationData.currentPage);
    }
  };

  const handlePaginationChange = (page) => {
    setPaginationData((prev) => ({ ...prev, currentPage: page }));
    fetchUserList(page);
  };

  useEffect(() => {
    fetchUserList(1);
    fetchAdminListLength();
  }, []);

  const columns = [
    {
      title: '账号',
      dataIndex: 'account',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
    },
    {
      title: '部门',
      dataIndex: 'department',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '状态',
      render: (text, record) => (
        <Tag color={record.status === 1 ? 'red' : 'green'}>
          {record.status === 1 ? '冻结' : '正常'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      render: (text, record) => <div>{record.createAt?.slice(0, 10)}</div>,
    },
    {
      title: '更新时间',
      render: (text, record) => <div>{record.updateAt?.slice(0, 10)}</div>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <div>
          <a onClick={() => banUserById(record.id)}>冻结</a>
          <a style={{ margin: '0px 10px' }} onClick={() => hotUserById(record.id)}>解冻</a>
          <a onClick={() => handleDeleteUser(record)} style={{ color: 'red' }}>删除</a>
        </div>
      ),
    },
  ];

  return (
    <div>
      <div className="table-wrapped">
        <div className="table-top">
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div className="search-wrapped">
                <Input
                  value={adminAccount}
                  onChange={(e) => setAdminAccount(e.target.value)}
                  style={{ width: 300 }}
                  size="large"
                  placeholder="输入账号进行搜索"
                  prefix={<SearchOutlined />}
                  onPressEnter={searchUserByAccount}
                />
              </div>
            </div>
            <div className="button-wrapped">
              <Button style={{ marginRight: 20 }} type="primary" onClick={banUserList}>
                筛选冻结用户
              </Button>
              <Button type="primary" onClick={() => fetchUserList(1)}>
                显示全部用户
              </Button>
            </div>
          </div>
          <div className="table-content">
            <Table
              columns={columns}
              dataSource={tableData}
              pagination={false}
              rowKey="id"
            />
          </div>
        </div>
        <div style={{
          display: 'flex',
          justifyContent: 'flex-end',
          marginTop: 20,
        }}>
          <Pagination
            pageSize={10}
            current={paginationData.currentPage}
            total={adminTotal}
            pageSizeOptions={['10', '20', '50']}
            onChange={handlePaginationChange}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
          />
        </div>
      </div>
    </div>
  );
};

export default UserList;
